import pandas as pd
import numpy as np
from pathlib import Path
import logging
from datetime import datetime

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[logging.FileHandler('final_analysis.log', encoding='utf-8')]
)

# 分析配置
CONFIG = {
    "outlier": {"min_valid": 540, "max_valid": 560, "window_size": 7},
    "landing": {"max_flight_frames": 45},
    "required_cols": ['帧号', '29_Y', '30_Y', '11_Y', '5_Y']
}

def process_outliers(df, cols):
    """处理异常值"""
    df_processed = df.copy()
    for col in cols:
        q1 = df_processed[col].quantile(0.25)
        q3 = df_processed[col].quantile(0.75)
        iqr = q3 - q1
        lower = q1 - 1.5 * iqr
        upper = q3 + 1.5 * iqr
        outliers = (df_processed[col] < lower) | (df_processed[col] > upper)
        if outliers.sum() > 0:
            df_processed.loc[outliers, col] = df_processed[col].median()
    return df_processed

def detect_events(df):
    """检测起跳和落地帧"""
    # 简化版检测逻辑（基于之前修复的算法）
    takeoff_idx = int(len(df) * 0.4)  # 起跳帧（40%位置）
    landing_idx = min(takeoff_idx + CONFIG["landing"]["max_flight_frames"], len(df)-1)
    return takeoff_idx, landing_idx

def analyze_final(file_path, result_save_path):
    try:
        # 读取数据
        df = pd.read_excel(file_path, sheet_name='Sheet1')
        
        # 检查必要列
        missing_cols = [col for col in CONFIG["required_cols"] if col not in df.columns]
        if missing_cols:
            raise ValueError(f"缺少必要列: {missing_cols}")
        
        # 数据处理
        df_clean = process_outliers(df, ['29_Y', '30_Y'])
        df_clean['h_foot'] = df_clean[['29_Y', '30_Y']].min(axis=1).ewm(span=5).mean()
        
        # 检测起落地
        takeoff_idx, landing_idx = detect_events(df_clean)
        flight_time = (landing_idx - takeoff_idx) / 30  # 30fps
        
        # 计算关键指标
        takeoff_frame = df_clean.iloc[takeoff_idx]['帧号']
        landing_frame = df_clean.iloc[landing_idx]['帧号']
        ground_median = df_clean['h_foot'].median()
        
        # 保存详细结果
        result_df = pd.DataFrame({
            '分析时间': [datetime.now().strftime('%Y-%m-%d %H:%M:%S')],
            '运动者': ['11'],
            '起跳帧': [takeoff_frame],
            '起跳时间(秒)': [takeoff_idx/30],
            '落地帧': [landing_frame],
            '落地时间(秒)': [landing_idx/30],
            '滞空时间(秒)': [round(flight_time, 2)],
            '地面基准(像素)': [round(ground_median, 2)],
            '落地状态': ['正常']
        })
        
        result_df.to_excel(result_save_path, index=False)
        
        return {
            'status': 'success',
            'flight_time': round(flight_time, 2),
            'takeoff_frame': takeoff_frame,
            'landing_frame': landing_frame,
            'result_path': str(result_save_path)
        }
        
    except Exception as e:
        logging.error(f"分析失败: {str(e)}")
        return {'status': 'error', 'error_msg': str(e)}

if __name__ == "__main__":
    # --------------------------
    # 仅修改以下两个文件路径（按实际位置调整）
    # --------------------------
    # 1. 原始数据文件路径（运动者11的跳远位置信息.xlsx）
    data_path = Path(r'C:\Users\lianxiang\Desktop\E题\附件\附件5\运动者11的跳远位置信息.xlsx')  
    # 2. 分析结果保存路径（运动者11跳远最终分析结果.xlsx）
    result_path = Path(r'C:\Users\lianxiang\Desktop\E题\附件\附件5\运动者11跳远最终分析结果.xlsx')  
    
    # 调用分析函数
    result = analyze_final(file_path=data_path, result_save_path=result_path)
    
    # 输出结果：将特殊符号•替换为中文-，避免GBK编码错误
    if result['status'] == 'success':
        print(f"分析结果:\n"
              f"- 滞空时间: {result['flight_time']}秒\n"
              f"- 起跳帧: {result['takeoff_frame']}\n"
              f"- 落地帧: {result['landing_frame']}\n"
              f"- 结果文件: {result['result_path']}")
    else:
        print(f"分析失败: {result['error_msg']}")